﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;

namespace NavsGo
{
    class ExtractIcon
    {
        public static Bitmap GetBitmapFromExeIcon(string path)
        {
            string bmp = path.Substring(0, path.LastIndexOf(".exe")) + ".bmp";
            GetBitmap(GetIconFromExe(path)).Save(bmp, System.Drawing.Imaging.ImageFormat.Bmp);
            return GetBitmap(GetIconFromExe(path));
        }

        public static Icon GetIconFromExe(string path)
        {
            return GetIconFromExe(path, true);
        }

        //http://www.pinvoke.net/default.aspx/shell32/ExtractIconEx.html
        public static Icon GetIconFromExe(string path, bool large)
        {
            IntPtr hLargeIcon = IntPtr.Zero;
            IntPtr hSmallIcon = IntPtr.Zero;
            ExtractIconEx(path, 0, ref hLargeIcon, ref hSmallIcon, 1);
            if (large)
            {
                return (Icon)Icon.FromHandle(hLargeIcon).Clone();
            }
            else
            {
                return (Icon)Icon.FromHandle(hSmallIcon).Clone();
            }
        }

        //http://social.msdn.microsoft.com/Forums/en-US/netfxcompact/thread/e765775c-a5b5-493f-baeb-3eaee1d41cef
        public static Bitmap GetBitmap(Icon icon)
        {
            Bitmap bmp = new Bitmap(icon.Width, icon.Height);
            
            //Create temporary graphics
            Graphics gxMem = Graphics.FromImage(bmp);

            //Draw the icon
            gxMem.DrawIcon(icon, 0, 0);

            //Clean up
            gxMem.Dispose();

            return bmp;
        }

        //http://msdn.microsoft.com/en-us/library/aa922154.aspx
        [DllImport("coredll.dll", SetLastError = true)]
        private static extern IntPtr ExtractIconEx(string fileName, int index, ref IntPtr hIconLarge, ref IntPtr hIconSmall, uint nIcons);
    }
}
